<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta 
    name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta 
    http-equiv="X-UA-Compatible" 
    content="ie=edge">
  <meta 
    name="theme-color" 
    content="#fff" 
    id="theme-color">
  <meta 
    name="description" 
    content="hexoDemo用于介绍如何使用hexo">
  <link 
    rel="icon" 
    href="/">
  <title>41-事件的绑定和事件对象Event</title>
  
    
      <meta 
        property="og:title" 
        content="41-事件的绑定和事件对象Event">
    
    
      <meta 
        property="og:url" 
        content="https://zwl5670.gitee.io/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/41-%E4%BA%8B%E4%BB%B6%E7%9A%84%E7%BB%91%E5%AE%9A%E5%92%8C%E4%BA%8B%E4%BB%B6%E5%AF%B9%E8%B1%A1Event/index.html">
    
    
      <meta 
        property="og:img" 
        content="https://img.songhn.com/img/Y67gdd.png">
    
    
      <meta 
        property="og:img" 
        content="hexoDemo用于介绍如何使用hexo">
    
    
      <meta 
        property="og:type" 
        content="article">
      <meta 
        property="og:article:published_time" 
        content="2004-03-01">
      <meta 
        property="og:article:modified_time" 
        content="2023-03-14">
      <meta 
        property="og:article:author" 
        content="zwl5670">
      
        
          <meta 
            property="og:article:tag" 
            content="JS基础">
        
      
    
  
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  <link rel="preload" href="/css/main.css" as="style" >
  
  <link rel="modulepreload" href="//instant.page/5.1.0">
  
  <link rel="stylesheet" href="/css/main.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">
  
  
  
    <link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">
  
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
    function loadCSS(href, data, attr) {
      var sheet = document.createElement('link');
      sheet.ref = 'stylesheet';
      sheet.href = href;
      sheet.dataset[data] = attr;
      document.head.appendChild(sheet);
    }
    function changeCSS(cssFile, data, attr) {
      var oldlink = document.querySelector(data);
      var newlink = document.createElement("link");
      newlink.setAttribute("rel", "stylesheet");
      newlink.setAttribute("href", cssFile);
      newlink.dataset.prism = attr;
      document.head.replaceChild(newlink, oldlink);
    }
  </script>
  
    
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
  </script>
  
    <script>
      var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
        document.getElementById('theme-color').dataset.mode = getCssMediaQuery();
      }
    };
    setDarkmode();
    </script>
  
  
  
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
<meta name="generator" content="Hexo 6.3.0"></head>

  <body>
    <div class="wrapper">
       
      <nav class="navbar">
  <div class="navbar-logo">
    <a class="navbar-logo-main" href="/">
      
      <span class="navbar-logo-dsc">前端面试</span>
      </a>
  </div>
  <div class="navbar-menu">
    
      <a 
        href="/" 
        class="navbar-menu-item">
        
          首页
        
      </a>
    
      <a 
        href="/archives" 
        class="navbar-menu-item">
        
          归档
        
      </a>
    
      <a 
        href="/tags" 
        class="navbar-menu-item">
        
          标签
        
      </a>
    
      <a 
        href="/categories" 
        class="navbar-menu-item">
        
          分类
        
      </a>
    
      <a 
        href="/about" 
        class="navbar-menu-item">
        
          关于
        
      </a>
    
      <a 
        href="/links" 
        class="navbar-menu-item">
        
          友链
        
      </a>
    
    <button 
      class="navbar-menu-item darknavbar navbar-menu-btn" 
      aria-label="Toggle dark mode"
      id="dark">
      <i class="iconfont icon-weather"></i>
    </button>
    <button 
      class="navbar-menu-item searchnavbar navbar-menu-btn" 
      aria-label="Toggle search"
      id="search">
      <!-- <i 
        class="iconfont icon-search" 
        style="font-size: 1.2rem; font-weight: 400;">
      </i> -->
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img"
        class="iconify iconify--ion" width="28" height="28" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512">
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M256 80a176 176 0 1 0 176 176A176 176 0 0 0 256 80Z"></path>
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M232 160a72 72 0 1 0 72 72a72 72 0 0 0-72-72Z"></path>
        <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="28"
          d="M283.64 283.64L336 336"></path>
      </svg>
    </button>
  </div>
</nav> 
      
      <div 
        id="local-search" 
        style="display: none">
        <input
          class="navbar-menu-item"
          id="search-input"
          placeholder="请输入搜索内容..." />
        <div id="search-content"></div>
      </div>
      
      <div class="section-wrap">
        <div class="container">
          <div class="columns">
            <aside class="left-column">
              
              <div class="card card-author">
                
  <img 
    src="https://img.songhn.com/img/Y67gdd.png" 
    class="author-img"
    width="88"
    height="88"
    alt="author avatar">

<p class="author-name">zwl5670</p>
<p class="author-description">前端学习资料</p>
<div class="author-message">
  <a 
    class="author-posts-count" 
    href="/archives">
    <span>215</span>
    <span>文章</span>
  </a>
  <a 
    class="author-categories-count" 
    href="/categories">
    <span>14</span>
    <span>分类</span>
  </a>
  <a 
    class="author-tags-count" 
    href="/tags">
    <span>14</span>
    <span>标签</span>
  </a>
</div>

              </div>
               <div class="sticky-tablet">
  
  
    <article class="display-when-two-columns spacer">
      <div class="card card-content toc-card">
        <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%91%E5%AE%9A%E4%BA%8B%E4%BB%B6%E7%9A%84%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F-x2F-DOM%E4%BA%8B%E4%BB%B6%E7%9A%84%E7%BA%A7%E5%88%AB"><span class="toc-text">绑定事件的两种方式&#x2F;DOM事件的级别</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#DOM0%E7%9A%84%E5%86%99%E6%B3%95%EF%BC%9Aonclick"><span class="toc-text">DOM0的写法：onclick</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DOM2%E7%9A%84%E5%86%99%E6%B3%95%EF%BC%9AaddEventListener%EF%BC%88%E9%AB%98%E7%89%88%E6%9C%AC%E6%B5%8F%E8%A7%88%E5%99%A8%EF%BC%89"><span class="toc-text">DOM2的写法：addEventListener（高版本浏览器）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DOM2%E7%9A%84%E5%86%99%E6%B3%95%EF%BC%9AattachEvent%EF%BC%88IE8%E5%8F%8A%E4%BB%A5%E4%B8%8B%E7%89%88%E6%9C%AC%E6%B5%8F%E8%A7%88%E5%99%A8%EF%BC%89"><span class="toc-text">DOM2的写法：attachEvent（IE8及以下版本浏览器）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%BC%E5%AE%B9%E6%80%A7%E5%86%99%E6%B3%95"><span class="toc-text">兼容性写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8B%E4%BB%B6%E5%AF%B9%E8%B1%A1"><span class="toc-text">事件对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96-event-%E5%AF%B9%E8%B1%A1%EF%BC%88%E5%85%BC%E5%AE%B9%E6%80%A7%E9%97%AE%E9%A2%98%EF%BC%89"><span class="toc-text">获取 event 对象（兼容性问题）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#event-%E5%B1%9E%E6%80%A7"><span class="toc-text">event 属性</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Event%E4%B8%BE%E4%BE%8B"><span class="toc-text">Event举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%BE%8B1%EF%BC%9A%E4%BD%BF-div-%E8%B7%9F%E9%9A%8F%E9%BC%A0%E6%A0%87%E7%A7%BB%E5%8A%A8"><span class="toc-text">举例1：使 div 跟随鼠标移动</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%BE%8B2%EF%BC%9A%E8%8E%B7%E5%8F%96%E9%BC%A0%E6%A0%87%E8%B7%9D%E7%A6%BB%E6%89%80%E5%9C%A8%E7%9B%92%E5%AD%90%E7%9A%84%E8%B7%9D%E7%A6%BB"><span class="toc-text">举例2：获取鼠标距离所在盒子的距离</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%BE%8B3%EF%BC%9A%E5%95%86%E5%93%81%E6%94%BE%E5%A4%A7%E9%95%9C"><span class="toc-text">举例3：商品放大镜</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
      </div>
    </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header">
    <i 
      class="iconfont icon-fenlei" 
      style="padding-right: 2px;">
    </i>分类
  </div>
  <div class="categories-list">
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/">
        <div class="categories-list-item">
          前端工具
          <span class="categories-list-item-badge">13</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          CSS基础
          <span class="categories-list-item-badge">18</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          CSS进阶
          <span class="categories-list-item-badge">9</span>
        </div>
      </a>
    
      <a href="/categories/HTML/">
        <div class="categories-list-item">
          HTML
          <span class="categories-list-item-badge">12</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          JS基础
          <span class="categories-list-item-badge">56</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80ES6/">
        <div class="categories-list-item">
          JS基础ES6
          <span class="categories-list-item-badge">10</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/">
        <div class="categories-list-item">
          JS基础异步
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/JS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          JS进阶
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/%E7%A7%BB%E5%8A%A8web/">
        <div class="categories-list-item">
          移动web
          <span class="categories-list-item-badge">3</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%92%8CDOM/">
        <div class="categories-list-item">
          CSS和DOM
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/Node/">
        <div class="categories-list-item">
          Node
          <span class="categories-list-item-badge">16</span>
        </div>
      </a>
    
      <a href="/categories/Vue%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          Vue基础
          <span class="categories-list-item-badge">15</span>
        </div>
      </a>
    
      <a href="/categories/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">
        <div class="categories-list-item">
          性能优化
          <span class="categories-list-item-badge">7</span>
        </div>
      </a>
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/">
        <div class="categories-list-item">
          前端工程化
          <span class="categories-list-item-badge">8</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header">
    <i 
      class="iconfont icon-biaoqian" 
      style="padding-right: 2px;">
    </i>热门标签
  </div>
  <div class="tags-list">
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80/" 
        title="JS基础">
        <div class="tags-list-item">JS基础</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%9F%BA%E7%A1%80/" 
        title="CSS基础">
        <div class="tags-list-item">CSS基础</div>
      </a>
    
      <a 
        href="/tags/Node/" 
        title="Node">
        <div class="tags-list-item">Node</div>
      </a>
    
      <a 
        href="/tags/Vue%E5%9F%BA%E7%A1%80/" 
        title="Vue基础">
        <div class="tags-list-item">Vue基础</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/" 
        title="前端工具">
        <div class="tags-list-item">前端工具</div>
      </a>
    
      <a 
        href="/tags/HTML/" 
        title="HTML">
        <div class="tags-list-item">HTML</div>
      </a>
    
      <a 
        href="/tags/JS%E8%BF%9B%E9%98%B6/" 
        title="JS进阶">
        <div class="tags-list-item">JS进阶</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
        title="JS基础异步">
        <div class="tags-list-item">JS基础异步</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80ES6/" 
        title="JS基础ES6">
        <div class="tags-list-item">JS基础ES6</div>
      </a>
    
      <a 
        href="/tags/CSS%E8%BF%9B%E9%98%B6/" 
        title="CSS进阶">
        <div class="tags-list-item">CSS进阶</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" 
        title="前端工程化">
        <div class="tags-list-item">前端工程化</div>
      </a>
    
      <a 
        href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" 
        title="性能优化">
        <div class="tags-list-item">性能优化</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%92%8CDOM/" 
        title="CSS和DOM">
        <div class="tags-list-item">CSS和DOM</div>
      </a>
    
      <a 
        href="/tags/%E7%A7%BB%E5%8A%A8web/" 
        title="移动web">
        <div class="tags-list-item">移动web</div>
      </a>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
            <main class="main-column">
              
<article class="card card-content">
  <header>
    <h1 class="post-title">
      41-事件的绑定和事件对象Event
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2004-02-29T16:00:00.000Z">
      <i 
        class="iconfont icon-calendar" 
        style="margin-right: 2px;">
      </i>
      <span>2004-03-01</span>
    </time>
    
      <span class="dot"></span>
      
        <a 
          href="/categories/JS%E5%9F%BA%E7%A1%80/" 
          class="post-meta-link">
          JS基础
        </a>
      
    
    
      <span class="dot"></span>
      <span>3.2k 字</span>
    
  </div>
  
    <div 
      class="post-meta post-show-meta" 
      style="margin-top: -10px;">
      <div style="display: flex; align-items: center;">
        <i 
          class="iconfont icon-biaoqian" 
          style="margin-right: 2px; font-size: 1.15rem;">
        </i>
        
          
          <a 
            href="/tags/JS%E5%9F%BA%E7%A1%80/" 
            class="post-meta-link">
            JS基础
          </a>
        
      </div>
    </div>
  
  </header>
  <div 
    id="section" 
    class="post-content">
    <p><ArticleTopAd></ArticleTopAd></p>
<h2 id="绑定事件的两种方式-x2F-DOM事件的级别"><a href="#绑定事件的两种方式-x2F-DOM事件的级别" class="headerlink" title="绑定事件的两种方式&#x2F;DOM事件的级别"></a>绑定事件的两种方式&#x2F;DOM事件的级别</h2><p>我们在之前的一篇文章《04-JavaScript&#x2F;22-DOM简介和DOM操作》中已经讲过事件的概念。这里讲一下绑定（注册）事件的两种方式，我们以onclick事件为例。</p>
<h3 id="DOM0的写法：onclick"><a href="#DOM0的写法：onclick" class="headerlink" title="DOM0的写法：onclick"></a>DOM0的写法：onclick</h3><pre class="highlight"><span class="line">element.<span class="property">onclick</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre>

<p>举例：</p>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span>&gt;</span>点我<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> btn = <span class="variable language_">document</span>.<span class="title function_">getElementsByTagName</span>(<span class="string">&quot;button&quot;</span>)[<span class="number">0</span>];</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//这种事件绑定的方式，如果绑定多个，则后面的会覆盖掉前面的</span></span></span><br><span class="line"><span class="language-javascript">    btn.<span class="property">onclick</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;事件1&quot;</span>);</span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    btn.<span class="property">onclick</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;事件2&quot;</span>);</span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br></pre>

<p>点击按钮后，上方代码的打印结果：</p>
<pre class="highlight"><span class="line">事件2</span><br></pre>

<p>我们可以看到，<code>DOM对象.事件 =  函数</code>的这种绑定事件的方式：一个元素的一个事件只能绑定一个响应函数。如果绑定了多个响应函数，则后者会覆盖前者。</p>
<h3 id="DOM2的写法：addEventListener（高版本浏览器）"><a href="#DOM2的写法：addEventListener（高版本浏览器）" class="headerlink" title="DOM2的写法：addEventListener（高版本浏览器）"></a>DOM2的写法：addEventListener（高版本浏览器）</h3><pre class="highlight"><span class="line">element.<span class="title function_">addEventListener</span>(<span class="string">&#x27;click&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line"></span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br></pre>


<p>参数解释：</p>
<ul>
<li><p>参数1：事件名的字符串(注意，没有on)</p>
</li>
<li><p>参数2：回调函数：当事件触发时，该函数会被执行</p>
</li>
<li><p>参数3：<strong>true表示捕获阶段触发，false表示冒泡阶段触发（默认）</strong>。如果不写，则默认为false。【重要】</p>
</li>
</ul>
<p>举例：</p>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span>&gt;</span>按钮<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> btn = <span class="variable language_">document</span>.<span class="title function_">getElementsByTagName</span>(<span class="string">&quot;button&quot;</span>)[<span class="number">0</span>];</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// addEventListener: 事件监听器。 原事件被执行的时候，后面绑定的事件照样被执行</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// 这种写法不存在响应函数被覆盖的情况。（更适合团队开发）</span></span></span><br><span class="line"><span class="language-javascript">    btn.<span class="title function_">addEventListener</span>(<span class="string">&quot;click&quot;</span>, fn1);</span></span><br><span class="line"><span class="language-javascript">    btn.<span class="title function_">addEventListener</span>(<span class="string">&quot;click&quot;</span>, fn2);</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">function</span> <span class="title function_">fn1</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;事件1&quot;</span>);</span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">function</span> <span class="title function_">fn2</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;事件2&quot;</span>);</span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br></pre>

<p>点击按钮后，上方代码的打印结果：</p>
<pre class="highlight"><span class="line">事件1</span><br><span class="line">事件2</span><br></pre>

<p>我们可以看到，<code>addEventListener()</code>这种绑定事件的方式：</p>
<ul>
<li><p>一个元素的一个事件，可以绑定多个响应函数。不存在响应函数被覆盖的情况。<strong>执行顺序是</strong>：事件被触发时，响应函数会按照函数的绑定顺序执行。</p>
</li>
<li><p>addEventListener()中的this，是绑定事件的对象。</p>
</li>
<li><p><code>addEventListener()</code>不支持 IE8 及以下的浏览器。在IE8中可以使用<code>attachEvent</code>来绑定事件（详见下一小段）。</p>
</li>
</ul>
<h3 id="DOM2的写法：attachEvent（IE8及以下版本浏览器）"><a href="#DOM2的写法：attachEvent（IE8及以下版本浏览器）" class="headerlink" title="DOM2的写法：attachEvent（IE8及以下版本浏览器）"></a>DOM2的写法：attachEvent（IE8及以下版本浏览器）</h3><pre class="highlight"><span class="line">element.<span class="title function_">attachEvent</span>(<span class="string">&#x27;onclick&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line"></span><br><span class="line">&#125;);</span><br><span class="line"></span><br></pre>

<p>参数解释：</p>
<ul>
<li><p>参数1：事件名的字符串(注意，有on)</p>
</li>
<li><p>参数2：回调函数：当事件触发时，该函数会被执行</p>
</li>
</ul>
<p>举例：</p>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span>&gt;</span>按钮<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">var</span> btn = <span class="variable language_">document</span>.<span class="title function_">getElementsByTagName</span>(<span class="string">&#x27;button&#x27;</span>)[<span class="number">0</span>];</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        btn.<span class="title function_">attachEvent</span>(<span class="string">&#x27;onclick&#x27;</span>, <span class="keyword">function</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;事件1&#x27;</span>);</span></span><br><span class="line"><span class="language-javascript">        &#125;);</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        btn.<span class="title function_">attachEvent</span>(<span class="string">&#x27;onclick&#x27;</span>, <span class="keyword">function</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;事件2&#x27;</span>);</span></span><br><span class="line"><span class="language-javascript">        &#125;);</span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br></pre>

<p>在低版本的IE浏览器上，点击按钮后，上方代码的打印结果：</p>
<pre class="highlight"><span class="line">事件2</span><br><span class="line">事件1</span><br></pre>

<p>我们可以看到，<code>attachEvent()</code>这种绑定事件的方式：</p>
<ul>
<li><p>一个元素的一个事件，可以绑定多个响应函数。不存在响应函数被覆盖的情况。<strong>注意</strong>：执行顺序是，后绑定的先执行。</p>
</li>
<li><p>attachEvent()中的this，是window</p>
</li>
</ul>
<h3 id="兼容性写法"><a href="#兼容性写法" class="headerlink" title="兼容性写法"></a>兼容性写法</h3><p>上面的内容里，需要强调的是：</p>
<ul>
<li><p><code>addEventListener()</code>中的this，是绑定事件的对象。</p>
</li>
<li><p><code>attachEvent()</code>中的this，是window。</p>
</li>
</ul>
<p>既然这两个写法的<code>this</code>不同，那么，有没有一种兼容性的写法可以确保这两种绑定方式的this是相同的呢？我们可以封装一下。代码如下：</p>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span>&gt;</span>按钮<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">var</span> btn = <span class="variable language_">document</span>.<span class="title function_">getElementsByTagName</span>(<span class="string">&#x27;button&#x27;</span>)[<span class="number">0</span>];</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="title function_">myBind</span>(btn , <span class="string">&quot;click&quot;</span> , <span class="keyword">function</span>(<span class="params"></span>)&#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="title function_">alert</span>(<span class="variable language_">this</span>);</span></span><br><span class="line"><span class="language-javascript">        &#125;);</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//定义一个函数，用来为指定元素绑定响应函数</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">/*</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         * addEventListener()中的this，是绑定事件的对象</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         * attachEvent()中的this，是window</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         *  需要统一两个方法this</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         */</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">/*</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         * 参数：</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         *  element 要绑定事件的对象</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         *  eventStr 事件的字符串(不要on)</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         *  callback 回调函数</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         */</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">function</span> <span class="title function_">myBind</span>(<span class="params">element , eventStr , callback</span>)&#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="keyword">if</span>(element.<span class="property">addEventListener</span>)&#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//大部分浏览器兼容的方式</span></span></span><br><span class="line"><span class="language-javascript">                element.<span class="title function_">addEventListener</span>(eventStr , callback , <span class="literal">false</span>);</span></span><br><span class="line"><span class="language-javascript">            &#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="comment">/*</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">                 * this是谁，由调用方式决定</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">                 * callback.call(element)</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">                 */</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//IE8及以下</span></span></span><br><span class="line"><span class="language-javascript">                element.<span class="title function_">attachEvent</span>(<span class="string">&quot;on&quot;</span>+eventStr , <span class="keyword">function</span>(<span class="params"></span>)&#123;</span></span><br><span class="line"><span class="language-javascript">                    <span class="comment">//在匿名函数 function 中调用回调函数callback</span></span></span><br><span class="line"><span class="language-javascript">                    callback.<span class="title function_">call</span>(element);</span></span><br><span class="line"><span class="language-javascript">                &#125;);</span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br></pre>


<h2 id="事件对象"><a href="#事件对象" class="headerlink" title="事件对象"></a>事件对象</h2><p>当事件的响应函数被触发时，会产生一个事件对象<code>event</code>。浏览器每次都会将这个事件<code>event</code>作为实参传进之前的响应函数。</p>
<p>这个对象中包含了与当前事件相关的一切信息。比如鼠标的坐标、键盘的哪个按键被按下、鼠标滚轮滚动的方向等。</p>
<h3 id="获取-event-对象（兼容性问题）"><a href="#获取-event-对象（兼容性问题）" class="headerlink" title="获取 event 对象（兼容性问题）"></a>获取 event 对象（兼容性问题）</h3><p>所有浏览器都支持event对象，但支持的方式不同。如下。</p>
<p>（1）普通浏览器的写法是 <code>event</code>。比如：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180203_1735.png" class="lozad post-image"src="http://img.smyhvae.com/20180203_1735.png"></p>
<p>（2）ie 678 的写法是 <code>window.event</code>。此时，事件对象 event 是作为window对象的属性保存的。</p>
<p>于是，我们可以采取一种兼容性的写法。如下：</p>
<pre class="highlight"><span class="line">event = event || <span class="variable language_">window</span>.<span class="property">event</span>; <span class="comment">// 兼容性写法</span></span><br></pre>

<p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//点击页面的任何部分</span></span></span><br><span class="line"><span class="language-javascript">    <span class="variable language_">document</span>.<span class="property">onclick</span> = <span class="keyword">function</span> (<span class="params">event</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        event = event || <span class="variable language_">window</span>.<span class="property">event</span>; <span class="comment">////兼容性写法</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">timeStamp</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">bubbles</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">button</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">pageX</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">pageY</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">screenX</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">screenY</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">target</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">type</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">clientX</span>);</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">console</span>.<span class="title function_">log</span>(event.<span class="property">clientY</span>);</span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>

<h3 id="event-属性"><a href="#event-属性" class="headerlink" title="event 属性"></a>event 属性</h3><p>event 有很多属性，比如：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180203_1739.png" class="lozad post-image"src="http://img.smyhvae.com/20180203_1739.png"></p>
<p>由于pageX 和 pageY的兼容性不好，我们可以这样做：</p>
<ul>
<li>鼠标在页面的位置 &#x3D; 滚动条滚动的距离 + 可视区域的坐标。</li>
</ul>
<h2 id="Event举例"><a href="#Event举例" class="headerlink" title="Event举例"></a>Event举例</h2><h3 id="举例1：使-div-跟随鼠标移动"><a href="#举例1：使-div-跟随鼠标移动" class="headerlink" title="举例1：使 div 跟随鼠标移动"></a>举例1：使 div 跟随鼠标移动</h3><p>代码实现：</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">style</span> <span class="attr">type</span>=<span class="string">&quot;text/css&quot;</span>&gt;</span><span class="language-css"></span></span><br><span class="line"><span class="language-css">      <span class="selector-id">#box1</span> &#123;</span></span><br><span class="line"><span class="language-css">        <span class="attribute">width</span>: <span class="number">100px</span>;</span></span><br><span class="line"><span class="language-css">        <span class="attribute">height</span>: <span class="number">100px</span>;</span></span><br><span class="line"><span class="language-css">        <span class="attribute">background-color</span>: red;</span></span><br><span class="line"><span class="language-css">        <span class="comment">/*</span></span></span><br><span class="line"><span class="comment"><span class="language-css">        * 开启box1的绝对定位</span></span></span><br><span class="line"><span class="comment"><span class="language-css">        */</span></span></span><br><span class="line"><span class="language-css">        <span class="attribute">position</span>: absolute;</span></span><br><span class="line"><span class="language-css">      &#125;</span></span><br><span class="line"><span class="language-css">    </span><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">      <span class="variable language_">window</span>.<span class="property">onload</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="comment">/*</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         * 使div可以跟随鼠标移动</span></span></span><br><span class="line"><span class="comment"><span class="language-javascript">         */</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//获取box1</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">var</span> box1 = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;box1&quot;</span>);</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//给整个页面绑定：鼠标移动事件</span></span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">document</span>.<span class="property">onmousemove</span> = <span class="keyword">function</span>(<span class="params">event</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">          <span class="comment">//兼容的方式获取event对象</span></span></span><br><span class="line"><span class="language-javascript">          event = event || <span class="variable language_">window</span>.<span class="property">event</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">          <span class="comment">// 鼠标在页面的位置 = 滚动条滚动的距离 + 可视区域的坐标。</span></span></span><br><span class="line"><span class="language-javascript">          <span class="keyword">var</span> pagex = event.<span class="property">pageX</span> || <span class="title function_">scroll</span>().<span class="property">left</span> + event.<span class="property">clientX</span>;</span></span><br><span class="line"><span class="language-javascript">          <span class="keyword">var</span> pagey = event.<span class="property">pageY</span> || <span class="title function_">scroll</span>().<span class="property">top</span> + event.<span class="property">clientY</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">          <span class="comment">//   设置div的偏移量（相对于整个页面）</span></span></span><br><span class="line"><span class="language-javascript">          <span class="comment">// 注意，如果想通过 style.left 来设置属性，一定要给 box1开启绝对定位。</span></span></span><br><span class="line"><span class="language-javascript">          box1.<span class="property">style</span>.<span class="property">left</span> = pagex + <span class="string">&quot;px&quot;</span>;</span></span><br><span class="line"><span class="language-javascript">          box1.<span class="property">style</span>.<span class="property">top</span> = pagey + <span class="string">&quot;px&quot;</span>;</span></span><br><span class="line"><span class="language-javascript">        &#125;;</span></span><br><span class="line"><span class="language-javascript">      &#125;;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">      <span class="comment">// scroll 函数封装</span></span></span><br><span class="line"><span class="language-javascript">      <span class="keyword">function</span> <span class="title function_">scroll</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="language-javascript">          <span class="comment">//此函数的返回值是对象</span></span></span><br><span class="line"><span class="language-javascript">          <span class="attr">left</span>: <span class="variable language_">window</span>.<span class="property">pageYOffset</span> || <span class="variable language_">document</span>.<span class="property">body</span>.<span class="property">scrollTop</span> || <span class="variable language_">document</span>.<span class="property">documentElement</span>.<span class="property">scrollTop</span>,</span></span><br><span class="line"><span class="language-javascript">          <span class="attr">right</span>:</span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">window</span>.<span class="property">pageXOffset</span> || <span class="variable language_">document</span>.<span class="property">body</span>.<span class="property">scrollLeft</span> || <span class="variable language_">document</span>.<span class="property">documentElement</span>.<span class="property">scrollLeft</span></span></span><br><span class="line"><span class="language-javascript">        &#125;;</span></span><br><span class="line"><span class="language-javascript">      &#125;</span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span> <span class="attr">style</span>=<span class="string">&quot;height: 1000px;width: 2000px;&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;box1&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>

<h3 id="举例2：获取鼠标距离所在盒子的距离"><a href="#举例2：获取鼠标距离所在盒子的距离" class="headerlink" title="举例2：获取鼠标距离所在盒子的距离"></a>举例2：获取鼠标距离所在盒子的距离</h3><p>关键点：</p>
<pre class="highlight"><span class="line">鼠标距离所在盒子的距离 = 鼠标在整个页面的位置 - 所在盒子在整个页面的位置</span><br></pre>

<p>代码演示：</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">style</span>&gt;</span><span class="language-css"></span></span><br><span class="line"><span class="language-css">        <span class="selector-class">.box</span> &#123;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">width</span>: <span class="number">300px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">height</span>: <span class="number">200px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">padding-top</span>: <span class="number">100px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">background-color</span>: pink;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">margin</span>: <span class="number">100px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">text-align</span>: center;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">font</span>: <span class="number">18px</span>/<span class="number">30px</span> <span class="string">&quot;simsun&quot;</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">cursor</span>: pointer;</span></span><br><span class="line"><span class="language-css">        &#125;</span></span><br><span class="line"><span class="language-css">    </span><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;box&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;animate.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//需求：鼠标进入盒子之后只要移动，哪怕1像素，随时显示鼠标在盒子中的坐标。</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//技术点：新事件，onmousemove：在事件源上，哪怕鼠标移动1像素也会触动这个事件。</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//一定程度上，模拟了定时器</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//步骤：</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//1.老三步和新五步</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//2.获取鼠标在整个页面的位置</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//3.获取盒子在整个页面的位置</span></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//4.用鼠标的位置减去盒子的位置赋值给盒子的内容。</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    <span class="comment">//1.老三步和新五步</span></span></span><br><span class="line"><span class="language-javascript">    <span class="keyword">var</span> div = <span class="variable language_">document</span>.<span class="title function_">getElementsByTagName</span>(<span class="string">&quot;div&quot;</span>)[<span class="number">0</span>];</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">    div.<span class="property">onmousemove</span> = <span class="keyword">function</span> (<span class="params">event</span>) &#123;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        event = event || <span class="variable language_">window</span>.<span class="property">event</span>;</span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//2.获取鼠标在整个页面的位置</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">var</span> pagex = event.<span class="property">pageX</span> || <span class="title function_">scroll</span>().<span class="property">left</span> + event.<span class="property">clientX</span>;</span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">var</span> pagey = event.<span class="property">pageY</span> || <span class="title function_">scroll</span>().<span class="property">top</span> + event.<span class="property">clientY</span>;</span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//3.获取盒子在整个页面的位置</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// var xx =</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">// var yy =</span></span></span><br><span class="line"><span class="language-javascript">        <span class="comment">//4.用鼠标的位置减去盒子的位置赋值给盒子的内容。</span></span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">var</span> targetx = pagex - div.<span class="property">offsetLeft</span>;</span></span><br><span class="line"><span class="language-javascript">        <span class="keyword">var</span> targety = pagey - div.<span class="property">offsetTop</span>;</span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">this</span>.<span class="property">innerHTML</span> = <span class="string">&quot;鼠标在盒子中的X坐标为：&quot;</span> + targetx + <span class="string">&quot;px;&lt;br&gt;鼠标在盒子中的Y坐标为：&quot;</span> + targety + <span class="string">&quot;px;&quot;</span></span></span><br><span class="line"><span class="language-javascript">    &#125;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>

<p>实现效果：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180203_1828.gif" class="lozad post-image"src="http://img.smyhvae.com/20180203_1828.gif"></p>
<h3 id="举例3：商品放大镜"><a href="#举例3：商品放大镜" class="headerlink" title="举例3：商品放大镜"></a>举例3：商品放大镜</h3><p>代码实现：</p>
<p>（1）index.html:</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">style</span>&gt;</span><span class="language-css"></span></span><br><span class="line"><span class="language-css">        * &#123;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">margin</span>: <span class="number">0</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">padding</span>: <span class="number">0</span>;</span></span><br><span class="line"><span class="language-css">        &#125;</span></span><br><span class="line"><span class="language-css"></span></span><br><span class="line"><span class="language-css">        <span class="selector-class">.box</span> &#123;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">width</span>: <span class="number">350px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">height</span>: <span class="number">350px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">margin</span>: <span class="number">100px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">border</span>: <span class="number">1px</span> solid <span class="number">#ccc</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">position</span>: relative;</span></span><br><span class="line"><span class="language-css">        &#125;</span></span><br><span class="line"><span class="language-css"></span></span><br><span class="line"><span class="language-css">        <span class="selector-class">.big</span> &#123;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">width</span>: <span class="number">400px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">height</span>: <span class="number">400px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">position</span>: absolute;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">top</span>: <span class="number">0</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">left</span>: <span class="number">360px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">border</span>: <span class="number">1px</span> solid <span class="number">#ccc</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">overflow</span>: hidden;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">display</span>: none;</span></span><br><span class="line"><span class="language-css">        &#125;</span></span><br><span class="line"><span class="language-css"></span></span><br><span class="line"><span class="language-css">        <span class="comment">/*mask的中文是：遮罩*/</span></span></span><br><span class="line"><span class="language-css">        <span class="selector-class">.mask</span> &#123;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">width</span>: <span class="number">175px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">height</span>: <span class="number">175px</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">background</span>: <span class="built_in">rgba</span>(<span class="number">255</span>, <span class="number">255</span>, <span class="number">0</span>, <span class="number">0.4</span>);</span></span><br><span class="line"><span class="language-css">            <span class="attribute">position</span>: absolute;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">top</span>: <span class="number">0</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">left</span>: <span class="number">0</span>;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">cursor</span>: move;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">display</span>: none;</span></span><br><span class="line"><span class="language-css">        &#125;</span></span><br><span class="line"><span class="language-css"></span></span><br><span class="line"><span class="language-css">        <span class="selector-class">.small</span> &#123;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">position</span>: relative;</span></span><br><span class="line"><span class="language-css">        &#125;</span></span><br><span class="line"><span class="language-css"></span></span><br><span class="line"><span class="language-css">        <span class="selector-tag">img</span> &#123;</span></span><br><span class="line"><span class="language-css">            <span class="attribute">vertical-align</span>: top;</span></span><br><span class="line"><span class="language-css">        &#125;</span></span><br><span class="line"><span class="language-css">    </span><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;tools.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">        <span class="variable language_">window</span>.<span class="property">onload</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//需求：鼠标放到小盒子上，让大盒子里面的图片和我们同步等比例移动。</span></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//技术点：onmouseenter==onmouseover 第一个不冒泡</span></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//技术点：onmouseleave==onmouseout  第一个不冒泡</span></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//步骤：</span></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//1.鼠标放上去显示盒子，移开隐藏盒子。</span></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//2.老三步和新五步（黄盒子跟随移动）</span></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//3.右侧的大图片，等比例移动。</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//0.获取相关元素</span></span></span><br><span class="line"><span class="language-javascript">            <span class="keyword">var</span> box = <span class="variable language_">document</span>.<span class="title function_">getElementsByClassName</span>(<span class="string">&quot;box&quot;</span>)[<span class="number">0</span>];</span></span><br><span class="line"><span class="language-javascript">            <span class="keyword">var</span> small = box.<span class="property">firstElementChild</span> || box.<span class="property">firstChild</span>;</span></span><br><span class="line"><span class="language-javascript">            <span class="keyword">var</span> big = box.<span class="property">children</span>[<span class="number">1</span>];</span></span><br><span class="line"><span class="language-javascript">            <span class="keyword">var</span> mask = small.<span class="property">children</span>[<span class="number">1</span>];</span></span><br><span class="line"><span class="language-javascript">            <span class="keyword">var</span> bigImg = big.<span class="property">children</span>[<span class="number">0</span>];</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//1.鼠标放上去显示盒子，移开隐藏盒子。(为小盒子绑定事件)</span></span></span><br><span class="line"><span class="language-javascript">            small.<span class="property">onmouseenter</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//封装好方法调用：显示元素</span></span></span><br><span class="line"><span class="language-javascript">                <span class="title function_">show</span>(mask);</span></span><br><span class="line"><span class="language-javascript">                <span class="title function_">show</span>(big);</span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">            small.<span class="property">onmouseleave</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//封装好方法调用：隐藏元素</span></span></span><br><span class="line"><span class="language-javascript">                <span class="title function_">hide</span>(mask);</span></span><br><span class="line"><span class="language-javascript">                <span class="title function_">hide</span>(big);</span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//2.老三步和新五步（黄盒子跟随移动）</span></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">//绑定的事件是onmousemove，而事件源是small(只要在小盒子上移动1像素，黄盒子也要跟随)</span></span></span><br><span class="line"><span class="language-javascript">            small.<span class="property">onmousemove</span> = <span class="keyword">function</span> (<span class="params">event</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//新五步</span></span></span><br><span class="line"><span class="language-javascript">                event = event || <span class="variable language_">window</span>.<span class="property">event</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//想要移动黄盒子，必须要知道鼠标在small小图中的位置。</span></span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">var</span> pagex = event.<span class="property">pageX</span> || <span class="title function_">scroll</span>().<span class="property">left</span> + event.<span class="property">clientX</span>;</span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">var</span> pagey = event.<span class="property">pageY</span> || <span class="title function_">scroll</span>().<span class="property">top</span> + event.<span class="property">clientY</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//x：mask的left值，y：mask的top值。</span></span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">var</span> x = pagex - box.<span class="property">offsetLeft</span> - mask.<span class="property">offsetWidth</span> / <span class="number">2</span>; <span class="comment">//除以2，可以保证鼠标mask的中间</span></span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">var</span> y = pagey - box.<span class="property">offsetTop</span> - mask.<span class="property">offsetHeight</span> / <span class="number">2</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//限制换盒子的范围</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//left取值为大于0，小盒子的宽-mask的宽。</span></span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">if</span> (x &lt; <span class="number">0</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                    x = <span class="number">0</span>;</span></span><br><span class="line"><span class="language-javascript">                &#125;</span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">if</span> (x &gt; small.<span class="property">offsetWidth</span> - mask.<span class="property">offsetWidth</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                    x = small.<span class="property">offsetWidth</span> - mask.<span class="property">offsetWidth</span>;</span></span><br><span class="line"><span class="language-javascript">                &#125;</span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//top同理。</span></span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">if</span> (y &lt; <span class="number">0</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                    y = <span class="number">0</span>;</span></span><br><span class="line"><span class="language-javascript">                &#125;</span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">if</span> (y &gt; small.<span class="property">offsetHeight</span> - mask.<span class="property">offsetHeight</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                    y = small.<span class="property">offsetHeight</span> - mask.<span class="property">offsetHeight</span>;</span></span><br><span class="line"><span class="language-javascript">                &#125;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//移动黄盒子</span></span></span><br><span class="line"><span class="language-javascript">                <span class="variable language_">console</span>.<span class="title function_">log</span>(small.<span class="property">offsetHeight</span>);</span></span><br><span class="line"><span class="language-javascript">                mask.<span class="property">style</span>.<span class="property">left</span> = x + <span class="string">&quot;px&quot;</span>;</span></span><br><span class="line"><span class="language-javascript">                mask.<span class="property">style</span>.<span class="property">top</span> = y + <span class="string">&quot;px&quot;</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//3.右侧的大图片，等比例移动。</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//如何移动大图片？等比例移动。</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//    大图片/大盒子 = 小图片/mask盒子</span></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//    大图片走的距离/mask走的距离 = （大图片-大盒子）/（小图片-黄盒子）</span></span></span><br><span class="line"><span class="language-javascript"><span class="comment">//                var bili = (bigImg.offsetWidth-big.offsetWidth)/(small.offsetWidth-mask.offsetWidth);</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">                <span class="comment">//大图片走的距离/mask盒子都的距离 = 大图片/小图片</span></span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">var</span> bili = bigImg.<span class="property">offsetWidth</span> / small.<span class="property">offsetWidth</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">var</span> xx = bili * x;  <span class="comment">//知道比例，就可以移动大图片了</span></span></span><br><span class="line"><span class="language-javascript">                <span class="keyword">var</span> yy = bili * y;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">                bigImg.<span class="property">style</span>.<span class="property">marginTop</span> = -yy + <span class="string">&quot;px&quot;</span>;</span></span><br><span class="line"><span class="language-javascript">                bigImg.<span class="property">style</span>.<span class="property">marginLeft</span> = -xx + <span class="string">&quot;px&quot;</span>;</span></span><br><span class="line"><span class="language-javascript">            &#125;</span></span><br><span class="line"><span class="language-javascript">        &#125;</span></span><br><span class="line"><span class="language-javascript">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;box&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;small&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">&quot;images/001.jpg&quot;</span> <span class="attr">alt</span>=<span class="string">&quot;&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;mask&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;big&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">&quot;images/0001.jpg&quot;</span> <span class="attr">alt</span>=<span class="string">&quot;&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>

<p>（2）tools.js:</p>
<pre class="highlight"><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Created by smyhvae on 2018/02/03.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//显示和隐藏</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">show</span>(<span class="params">ele</span>) &#123;</span><br><span class="line">    ele.<span class="property">style</span>.<span class="property">display</span> = <span class="string">&quot;block&quot;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">hide</span>(<span class="params">ele</span>) &#123;</span><br><span class="line">    ele.<span class="property">style</span>.<span class="property">display</span> = <span class="string">&quot;none&quot;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">scroll</span>(<span class="params"></span>) &#123;  <span class="comment">// 开始封装自己的scrollTop</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="variable language_">window</span>.<span class="property">pageYOffset</span> != <span class="literal">null</span>) &#123;  <span class="comment">// ie9+ 高版本浏览器</span></span><br><span class="line">        <span class="comment">// 因为 window.pageYOffset 默认的是  0  所以这里需要判断</span></span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            <span class="attr">left</span>: <span class="variable language_">window</span>.<span class="property">pageXOffset</span>,</span><br><span class="line">            <span class="attr">top</span>: <span class="variable language_">window</span>.<span class="property">pageYOffset</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable language_">document</span>.<span class="property">compatMode</span> === <span class="string">&quot;CSS1Compat&quot;</span>) &#123;    <span class="comment">// 标准浏览器   来判断有没有声明DTD</span></span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            <span class="attr">left</span>: <span class="variable language_">document</span>.<span class="property">documentElement</span>.<span class="property">scrollLeft</span>,</span><br><span class="line">            <span class="attr">top</span>: <span class="variable language_">document</span>.<span class="property">documentElement</span>.<span class="property">scrollTop</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> &#123;   <span class="comment">// 未声明 DTD</span></span><br><span class="line">        <span class="attr">left</span>: <span class="variable language_">document</span>.<span class="property">body</span>.<span class="property">scrollLeft</span>,</span><br><span class="line">        <span class="attr">top</span>: <span class="variable language_">document</span>.<span class="property">body</span>.<span class="property">scrollTop</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre>

<p>效果演示：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180203_1920.gif" class="lozad post-image"src="http://img.smyhvae.com/20180203_1920.gif"></p>
<h2 id="我的公众号"><a href="#我的公众号" class="headerlink" title="我的公众号"></a>我的公众号</h2><p>想学习<font color=#0000ff><strong>更多技能</strong></font>？不妨关注我的微信公众号：<strong>千古壹号</strong>（id：<code>qianguyihao</code>）。</p>
<p>扫一扫，你将发现另一个全新的世界，而这将是一场美丽的意外：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/2016040102.jpg" class="lozad post-image"src="http://img.smyhvae.com/2016040102.jpg"></p>

  </div>
  <div>
    
      <div 
        class="post-note note-warning copyright" 
        style="margin-top: 42px">
        <p>
          <span style="font-weight: bold;">作者：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="/about">
            zwl5670
          </a>
        </p>
        <p>
          <span style="font-weight: bold;">文章链接：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="https://zwl5670.gitee.io/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/41-%E4%BA%8B%E4%BB%B6%E7%9A%84%E7%BB%91%E5%AE%9A%E5%92%8C%E4%BA%8B%E4%BB%B6%E5%AF%B9%E8%B1%A1Event/">
            https://zwl5670.gitee.io/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/41-%E4%BA%8B%E4%BB%B6%E7%9A%84%E7%BB%91%E5%AE%9A%E5%92%8C%E4%BA%8B%E4%BB%B6%E5%AF%B9%E8%B1%A1Event/
          </a>
        </p>
        <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
      </div>
    
  </div>
</article>
<div class="nav">
  
    <div class="nav-item-prev">
      <a 
        href="/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/40-client%EF%BC%88%E5%8F%AF%E8%A7%86%E5%8C%BA%EF%BC%89%E7%9B%B8%E5%85%B3%E5%B1%9E%E6%80%A7/" 
        class="nav-link">
        <i class="iconfont icon-left nav-prev-icon"></i>
        <div>
          <div class="nav-label">上一篇</div>
          
            <div class="nav-title">40-client（可视区）相关属性 </div>
          
        </div>
      </a>
    </div>
  
  
    <div class="nav-item-next">
      <a 
        href="/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/39-scroll%E7%9B%B8%E5%85%B3%E5%B1%9E%E6%80%A7%E5%92%8C%E7%BC%93%E5%8A%A8%E5%8A%A8%E7%94%BB/" 
        class="nav-link">
        <div>
          <div class="nav-label">下一篇</div>
          
            <div class="nav-title">39-scroll相关属性和缓动动画 </div>
          
        </div>
        <i class="iconfont icon-right nav-next-icon"></i>
      </a>
    </div>
  
</div>

<div 
  class="card card-content toc-card" 
  id="mobiletoc">
  <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%91%E5%AE%9A%E4%BA%8B%E4%BB%B6%E7%9A%84%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F-x2F-DOM%E4%BA%8B%E4%BB%B6%E7%9A%84%E7%BA%A7%E5%88%AB"><span class="toc-text">绑定事件的两种方式&#x2F;DOM事件的级别</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#DOM0%E7%9A%84%E5%86%99%E6%B3%95%EF%BC%9Aonclick"><span class="toc-text">DOM0的写法：onclick</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DOM2%E7%9A%84%E5%86%99%E6%B3%95%EF%BC%9AaddEventListener%EF%BC%88%E9%AB%98%E7%89%88%E6%9C%AC%E6%B5%8F%E8%A7%88%E5%99%A8%EF%BC%89"><span class="toc-text">DOM2的写法：addEventListener（高版本浏览器）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DOM2%E7%9A%84%E5%86%99%E6%B3%95%EF%BC%9AattachEvent%EF%BC%88IE8%E5%8F%8A%E4%BB%A5%E4%B8%8B%E7%89%88%E6%9C%AC%E6%B5%8F%E8%A7%88%E5%99%A8%EF%BC%89"><span class="toc-text">DOM2的写法：attachEvent（IE8及以下版本浏览器）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%BC%E5%AE%B9%E6%80%A7%E5%86%99%E6%B3%95"><span class="toc-text">兼容性写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8B%E4%BB%B6%E5%AF%B9%E8%B1%A1"><span class="toc-text">事件对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96-event-%E5%AF%B9%E8%B1%A1%EF%BC%88%E5%85%BC%E5%AE%B9%E6%80%A7%E9%97%AE%E9%A2%98%EF%BC%89"><span class="toc-text">获取 event 对象（兼容性问题）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#event-%E5%B1%9E%E6%80%A7"><span class="toc-text">event 属性</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Event%E4%B8%BE%E4%BE%8B"><span class="toc-text">Event举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%BE%8B1%EF%BC%9A%E4%BD%BF-div-%E8%B7%9F%E9%9A%8F%E9%BC%A0%E6%A0%87%E7%A7%BB%E5%8A%A8"><span class="toc-text">举例1：使 div 跟随鼠标移动</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%BE%8B2%EF%BC%9A%E8%8E%B7%E5%8F%96%E9%BC%A0%E6%A0%87%E8%B7%9D%E7%A6%BB%E6%89%80%E5%9C%A8%E7%9B%92%E5%AD%90%E7%9A%84%E8%B7%9D%E7%A6%BB"><span class="toc-text">举例2：获取鼠标距离所在盒子的距离</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%BE%8B3%EF%BC%9A%E5%95%86%E5%93%81%E6%94%BE%E5%A4%A7%E9%95%9C"><span class="toc-text">举例3：商品放大镜</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
</div>
            </main>
            <aside class="right-column">
              <div class="sticky-widescreen">
  
  
    <article class="card card-content toc-card">
      <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%91%E5%AE%9A%E4%BA%8B%E4%BB%B6%E7%9A%84%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F-x2F-DOM%E4%BA%8B%E4%BB%B6%E7%9A%84%E7%BA%A7%E5%88%AB"><span class="toc-text">绑定事件的两种方式&#x2F;DOM事件的级别</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#DOM0%E7%9A%84%E5%86%99%E6%B3%95%EF%BC%9Aonclick"><span class="toc-text">DOM0的写法：onclick</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DOM2%E7%9A%84%E5%86%99%E6%B3%95%EF%BC%9AaddEventListener%EF%BC%88%E9%AB%98%E7%89%88%E6%9C%AC%E6%B5%8F%E8%A7%88%E5%99%A8%EF%BC%89"><span class="toc-text">DOM2的写法：addEventListener（高版本浏览器）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DOM2%E7%9A%84%E5%86%99%E6%B3%95%EF%BC%9AattachEvent%EF%BC%88IE8%E5%8F%8A%E4%BB%A5%E4%B8%8B%E7%89%88%E6%9C%AC%E6%B5%8F%E8%A7%88%E5%99%A8%EF%BC%89"><span class="toc-text">DOM2的写法：attachEvent（IE8及以下版本浏览器）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%BC%E5%AE%B9%E6%80%A7%E5%86%99%E6%B3%95"><span class="toc-text">兼容性写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8B%E4%BB%B6%E5%AF%B9%E8%B1%A1"><span class="toc-text">事件对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96-event-%E5%AF%B9%E8%B1%A1%EF%BC%88%E5%85%BC%E5%AE%B9%E6%80%A7%E9%97%AE%E9%A2%98%EF%BC%89"><span class="toc-text">获取 event 对象（兼容性问题）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#event-%E5%B1%9E%E6%80%A7"><span class="toc-text">event 属性</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Event%E4%B8%BE%E4%BE%8B"><span class="toc-text">Event举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%BE%8B1%EF%BC%9A%E4%BD%BF-div-%E8%B7%9F%E9%9A%8F%E9%BC%A0%E6%A0%87%E7%A7%BB%E5%8A%A8"><span class="toc-text">举例1：使 div 跟随鼠标移动</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%BE%8B2%EF%BC%9A%E8%8E%B7%E5%8F%96%E9%BC%A0%E6%A0%87%E8%B7%9D%E7%A6%BB%E6%89%80%E5%9C%A8%E7%9B%92%E5%AD%90%E7%9A%84%E8%B7%9D%E7%A6%BB"><span class="toc-text">举例2：获取鼠标距离所在盒子的距离</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BE%E4%BE%8B3%EF%BC%9A%E5%95%86%E5%93%81%E6%94%BE%E5%A4%A7%E9%95%9C"><span class="toc-text">举例3：商品放大镜</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
    </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header">
    <i 
      class="iconfont icon-wenzhang_huaban" 
      style="padding-right: 2px;">
    </i>最近文章
  </div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/11-React%20Navive%E5%88%9D%E8%AF%86/"><div class="recent-posts-item-content">11-React Navive初识</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/10-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E4%BD%BF%E7%94%A8customRequest%E6%96%B9%E6%B3%95%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%8A%E4%BC%A0%E8%A1%8C%E4%B8%BA/"><div class="recent-posts-item-content">10-AntD框架的upload组件上传图片时使用customRequest方法自定义上传行为</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/09-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E9%81%87%E5%88%B0%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91/"><div class="recent-posts-item-content">09-AntD框架的upload组件上传图片时遇到的一些坑</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/08-Ant%20Design%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/"><div class="recent-posts-item-content">08-Ant Design的基本使用</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
          </div>
        </div>
      </div>
    </div>
     
    <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>
          Copyright ©
          
            2023
          
          
        </span>
        &nbsp;
        <a 
          href="/" 
          class="footer-link">
          前端面试
        </a>
      </div>
    </div>

    
      <div class="footer-dsc">
        
          Powered by
          <a 
            href="https://hexo.io/" 
            class="footer-link" 
            target="_blank" 
            rel="nofollow noopener noreferrer">
            &nbsp;Hexo
          </a>
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          Theme -
          <a 
            href="https://github.com/theme-kaze" 
            class="footer-link" 
            target="_blank"
            rel="nofollow noopener noreferrer">
            &nbsp;Kaze
          </a>
        
      </div>
    
    
    
    
</footer>
 
    
  <a 
    role="button" 
    id="scrollbutton" 
    class="basebutton" 
    aria-label="回到顶部">
    <i class="iconfont icon-arrowleft button-icon"></i>
  </a>

<a 
  role="button" 
  id="menubutton"
  aria-label="menu button"
  class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a 
  role="button" 
  id="popbutton" 
  class="basebutton" 
  aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a 
  role="button" 
  id="darkbutton" 
  class="basebutton darkwidget" 
  aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a 
  role="button" 
  id="searchbutton" 
  class="basebutton searchwidget" 
  aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a> 
     
     
     
      <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img')
    var i
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a')
      wrapper.setAttribute('href', img[i].getAttribute('data-src'))
      wrapper.setAttribute('aria-label', 'illustration')
      wrapper.style.cssText =
        'width: 100%; display: flex; justify-content: center;'
      if (img[i].alt) wrapper.dataset.caption = img[i].alt
      wrapper.dataset.nolink = true
      img[i].before(wrapper)
      wrapper.append(img[i])
      var divWrap = document.createElement('div')
      divWrap.classList.add('gallery')
      wrapper.before(divWrap)
      divWrap.append(wrapper)
    }
    baguetteBox.run('.gallery')
  }
</script>
<script>
  loadScript(
    "/js/lib/lightbox/baguetteBox.min.js",
    addImgLayout
  )
</script>
 
     
     
    <script src="/js/main.js"></script> 
     
    
      <script>
        var addLazyload = function () {
          var observer = lozad('.lozad', {
            load: function (el) {
              el.srcset = el.getAttribute('data-src')
            },
            loaded: function (el) {
              el.classList.add('loaded')
            },
          })
          observer.observe()
        }
      </script>
      <script>
        loadScript('/js/lib/lozad.min.js', addLazyload)
      </script>
    
    <script src="//instant.page/5.1.0" type="module"
      integrity="sha384-by67kQnR+pyfy8yWP4kPO12fHKRLHZPfEsiSXR8u2IKcTdxD805MGUXBzVPnkLHw"></script>
    
    
  </body>
</html>
